﻿using System;
using System.Collections.Generic;
using System.Web;
using BusinessLogic.BusinessRules;
using BusinessLogic.ClassFactory;
using System.Data;
using System.Xml;
using HtmlAgilityPack;

namespace Util.CustomForm
{
    public class CustomForm
    {
        #region 字段 属性
        private int _intSectionId;
        private string _strReceiveHtmlDoc;
        public int SectionId
        {
            get { return _intSectionId; }
            set { _intSectionId = value; }
        }
        public string ReceiveHtmlDoc
        {
            get { return _strReceiveHtmlDoc; }
            set { _strReceiveHtmlDoc = value; }
        }
        #endregion

        public CustomForm(int intSectionId, string strHtmlDoc)
        {
            _intSectionId = intSectionId;
            _strReceiveHtmlDoc = strHtmlDoc;
        }

        /// <summary>
        /// 解析数据源并返回解析后数据
        /// </summary>
        /// <param name="strResultSaveNode">经过解析的节点集</param>
        /// <param name="strSaveXmlDoc">解析后的数据文档</param>
        /// <returns>是否成功</returns>
        public bool SaveDatabyDataNodel(ref string strResultSaveNode,ref string strSaveXmlDoc)
        {
            try
            {
                using (SectionsFactory objSectionFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(_intSectionId);
                    if (objSections != null)
                    {
                        DataTable tblTmp = objSections.Data.Tables[0];
                        DataRow row = tblTmp.Rows[0];
                        string strDatamodle = row["chvDataModel"] == DBNull.Value ? "" : objSections.DataItem.chvDataModel;
                        string strDataPrototype = row["chvDataPrototype"] == DBNull.Value ? "" : objSections.DataItem.chvDataPrototype;
                        if (String.IsNullOrEmpty(strDatamodle) || string.IsNullOrEmpty(strDataPrototype))
                        {
                            throw new Exception("ID为" + _intSectionId + "的栏目不存在数据模型或数据原型");
                        }
                        else
                        {
                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.LoadXml(strDatamodle);
                            XmlNode rootNode = xmlDoc.SelectSingleNode("//datamodel");
                            if (rootNode == null)
                            {
                                throw new Exception("ID为" + _intSectionId + "的数据模型文档不存在数据根节点");
                            }
                            else
                            {
                                if (!rootNode.HasChildNodes)
                                {
                                    throw new Exception("ID为" + _intSectionId + "数据模型中不包含具体数据项");
                                }
                                else
                                {
                                    XmlNodeList dataNodeList = rootNode.ChildNodes;
                                    HtmlDocument htmlDoc = new HtmlDocument();
                                    htmlDoc.LoadHtml(_strReceiveHtmlDoc.ToLower());
                                    int intSaveNodeSize = 0;
                                    strResultSaveNode="";
                                    foreach (XmlNode xmlNode in dataNodeList)
                                    {
                                        string strXPath = "//*[@id='" + xmlNode.Name + "']";
                                        HtmlNode htmldatanode = htmlDoc.DocumentNode.SelectSingleNode(strXPath);
                                        if (htmldatanode != null)
                                        {
                                            XmlCDataSection xmlCData=xmlDoc.CreateCDataSection(htmldatanode.InnerHtml);
                                            xmlNode.AppendChild(xmlCData);
                                            intSaveNodeSize = intSaveNodeSize + 1;
                                            strResultSaveNode = strResultSaveNode + xmlNode.Name+",";
                                        }
                                    }
                                    if (intSaveNodeSize == 0)
                                    {
                                        throw new Exception("ID为" + _intSectionId + "的数据模型没有从数据来源中找到可匹配的数据");
                                    }
                                    else
                                    {
                                        strResultSaveNode=strResultSaveNode.Remove(strResultSaveNode.LastIndexOf(','));
                                        strSaveXmlDoc = xmlDoc.OuterXml;
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("ID为" + _intSectionId + "的栏目不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 解析数据源并返回解析后数据
        /// </summary>
        /// <param name="strSaveXmlDoc">解析后的数据文档</param>
        /// <returns>是否成功</returns>
        public bool SaveDatabyDataNodel( ref string strSaveXmlDoc)
        {
            try
            {
                using (SectionsFactory objSectionFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(_intSectionId);
                    if (objSections != null)
                    {
                        DataTable tblTmp = objSections.Data.Tables[0];
                        DataRow row = tblTmp.Rows[0];
                        string strDatamodle = row["chvDataModel"] == DBNull.Value ? "" : objSections.DataItem.chvDataModel;
                        string strDataPrototype = row["chvDataPrototype"] == DBNull.Value ? "" : objSections.DataItem.chvDataPrototype;
                        if (String.IsNullOrEmpty(strDatamodle) || string.IsNullOrEmpty(strDataPrototype))
                        {
                            throw new Exception("ID为" + _intSectionId + "的栏目不存在数据模型或数据原型");
                        }
                        else
                        {
                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.LoadXml(strDatamodle);
                            XmlNode rootNode = xmlDoc.SelectSingleNode("//datamodel");
                            if (rootNode == null)
                            {
                                throw new Exception("ID为" + _intSectionId + "的数据模型文档不存在数据根节点");
                            }
                            else
                            {
                                if (!rootNode.HasChildNodes)
                                {
                                    throw new Exception("ID为" + _intSectionId + "数据模型中不包含具体数据项");
                                }
                                else
                                {
                                    XmlNodeList dataNodeList = rootNode.ChildNodes;
                                    HtmlDocument htmlDoc = new HtmlDocument();
                                    htmlDoc.LoadHtml(_strReceiveHtmlDoc.ToLower());
                                    int intSaveNodeSize = 0;
                                    foreach (XmlNode xmlNode in dataNodeList)
                                    {
                                        string strXPath = "//*[@id='" + xmlNode.Name + "']";
                                        HtmlNode htmldatanode = htmlDoc.DocumentNode.SelectSingleNode(strXPath);
                                        if (htmldatanode != null)
                                        {
                                            XmlCDataSection xmlCData = xmlDoc.CreateCDataSection(htmldatanode.InnerHtml);
                                            xmlNode.AppendChild(xmlCData);
                                            intSaveNodeSize = intSaveNodeSize + 1;
                                        }
                                    }
                                    if (intSaveNodeSize == 0)
                                    {
                                        throw new Exception("ID为" + _intSectionId + "的数据模型没有从数据来源中找到可匹配的数据");
                                    }
                                    else
                                    {
                                        strSaveXmlDoc = xmlDoc.OuterXml;
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("ID为" + _intSectionId + "的栏目不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 解析数据源并返回解析后数据
        /// </summary>
        /// <param name="dataChangeCount">经过解析的节点集数</param>
        /// <param name="strSaveXmlDoc">解析后的数据文档</param>
        /// <returns>是否成功</returns>
        public bool SaveDatabyDataNodel(ref int dataChangeCount,ref string strSaveXmlDoc)
        {
            try
            {
                using (SectionsFactory objSectionFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objSections = objSectionFactory.Creator(_intSectionId);
                    if (objSections != null)
                    {
                        DataTable tblTmp = objSections.Data.Tables[0];
                        DataRow row = tblTmp.Rows[0];
                        string strDatamodle = row["chvDataModel"] == DBNull.Value ? "" : objSections.DataItem.chvDataModel;
                        string strDataPrototype = row["chvDataPrototype"] == DBNull.Value ? "" : objSections.DataItem.chvDataPrototype;
                        if (String.IsNullOrEmpty(strDatamodle) || string.IsNullOrEmpty(strDataPrototype))
                        {
                            throw new Exception("ID为" + _intSectionId + "的栏目不存在数据模型或数据原型");
                        }
                        else
                        {
                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.LoadXml(strDatamodle);
                            XmlNode rootNode = xmlDoc.SelectSingleNode("//datamodel");
                            if (rootNode == null)
                            {
                                throw new Exception("ID为" + _intSectionId + "的数据模型文档不存在数据根节点");
                            }
                            else
                            {
                                if (!rootNode.HasChildNodes)
                                {
                                    throw new Exception("ID为" + _intSectionId + "数据模型中不包含具体数据项");
                                }
                                else
                                {
                                    XmlNodeList dataNodeList = rootNode.ChildNodes;
                                    HtmlDocument htmlDoc = new HtmlDocument();
                                    htmlDoc.LoadHtml(_strReceiveHtmlDoc.ToLower());
                                    int intSaveNodeSize = 0;
                                    foreach (XmlNode xmlNode in dataNodeList)
                                    {
                                        string strXPath = "//*[@id='" + xmlNode.Name + "']";
                                        HtmlNode htmldatanode = htmlDoc.DocumentNode.SelectSingleNode(strXPath);
                                        if (htmldatanode != null)
                                        {
                                            XmlCDataSection xmlCData = xmlDoc.CreateCDataSection(htmldatanode.InnerHtml);
                                            xmlNode.AppendChild(xmlCData);
                                            intSaveNodeSize = intSaveNodeSize + 1;
                                        }
                                    }
                                    if (intSaveNodeSize == 0)
                                    {
                                        throw new Exception("ID为" + _intSectionId + "的数据模型没有从数据来源中找到可匹配的数据");
                                    }
                                    else
                                    {
                                        dataChangeCount = intSaveNodeSize;
                                        strSaveXmlDoc = xmlDoc.OuterXml;
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("ID为" + _intSectionId + "的栏目不存在");
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}